<template>
  <div class="dzpage" v-loading="loading" element-loading-text="上传文件中...">
    <div class="leftbox">
      <div class="image-viewer-container">
        <!-- 主图片容器 -->
        <div
          class="image-container"
          @wheel="handleWheel"
          @mousedown="startDrag"
          @mousemove="handleDrag"
          @mouseup="endDrag"
          @mouseleave="endDrag"
        >
          <el-image ref="imageRef" :style="imageStyle" :src="srcimg || ''" :preview-src-list="fdlsit" fit="contain" />
        </div>

        <!-- 控制按钮 -->
        <div class="controls">
          <el-button-group>
            <el-button @click="zoom(0.2)" :icon="ZoomIn" title="放大" />
            <el-button @click="zoom(-0.2)" :icon="ZoomOut" title="缩小" />
            <el-button @click="reset" :icon="RefreshLeft" title="重置" />
          </el-button-group>
          <span class="scale-text">缩放: {{ (scale * 100).toFixed(0) }}%</span>
        </div>
      </div>
      <div class="xybox">
        <div class="imguploadbox">
          <label for="customFileInput" class="input-file input-fileup">
            <i class="iconfont icon-beike"></i>
            <span class="imgrext"> 上传多个文件</span>
          </label>

          <input
            id="customFileInput"
            ref="file"
            class="fileUploaderClass"
            type="file"
            name="files"
            multiple
            accept="image/*"
            style="position: absolute; left: -9999px"
            @change.stop="handleFileSelect"
          />
        </div>
        <div>
          <el-button type="primary" @click="scbutton()">删除</el-button>
        </div>
        <div>
          <el-button type="primary" @click="xybutton">上一张</el-button>
          <span class="yebox">第{{ yepage + 1 }}/{{ srcList.length }}张</span>
          <el-button type="primary" @click="sybutton">下一张</el-button>
        </div>
      </div>
    </div>
    <div class="rightbox">
      <el-form :model="formlist" label-width="auto" style="max-width: 700px">
        <el-form-item label="姓名">
          <el-select v-model="formlist.patientId" placeholder="" style="width: 240px" filterable>
            <el-option v-for="item in hznamelist" :key="item.patientId" :label="item.patientName" :value="item.patientId" />
          </el-select>
        </el-form-item>
        <el-form-item label="检查时间" prop="examinationTime">
          <el-date-picker v-model="formlist.examinationTime" value-format="YYYY-MM-DD" type="date" style="width: 240px" />
        </el-form-item>

        <el-form-item label="检查部位" prop="examinationPart">
          <el-radio-group v-model="formlist.examinationPart" @change="ybchangetwo">
            <el-radio v-for="item in jcbwlist" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue" size="large">
              {{ item.dictLabel }}
            </el-radio>
          </el-radio-group>
          <el-input v-model="formlist.examinationOther" placeholder="" style="width: 200px" clearable :disabled="showzz" />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="formlist.remark" type="textarea" />
        </el-form-item>

        <el-form-item label="检查情况" prop="inspectSituation">
          <el-select v-model="formlist.inspectSituation" placeholder="">
            <el-option v-for="item in jcqklist" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue" />
          </el-select>
        </el-form-item>

        <div class="bcbox">
          <el-button type="primary" @click="savebutton">保存</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from "vue";
import { seekdataApi, dguploadAPI, imageslist, deletezpApi } from "@/api/system/system.js";
import { ElMessage, ElMessageBox } from "element-plus";
import { addhydApi } from "@/api/hzmange/index.js";
import { getMonthlyGrowth } from "@/api/jzglmange/index.js";
import { getjxxxListApi, addjxxxApi } from "@/api/hzmange/index.js";
import { ZoomIn, ZoomOut, Refresh, RefreshLeft } from "@element-plus/icons-vue";

const srcimg = ref(""); // 显式初始化为空字符串
const yepage = ref(0);

const imageRef = ref(null);
const scale = ref(1);
const flipX = ref(1); // 1=正常，-1=水平翻转

const isDragging = ref(false);
const startPos = ref({ x: 0, y: 0 });
const currentPos = ref({ x: 0, y: 0 });
const fdlsit = ref([]);
const srcList = ref([]);
let formlist = ref({});
let tableData = ref([]);
let hyxmlist = ref([]);
const loading = ref(false);

const props = defineProps({
  src: String // 图片URL
});
// 动态图片样式 计算属性
const imageStyle = computed(() => ({
  transform: `scale(${scale.value}) scaleX(${flipX.value}) translate(${currentPos.value.x}px, ${currentPos.value.y}px)`,
  transformOrigin: "center center",
  transition: isDragging.value ? "none" : "transform 0.3s ease",
  cursor: isDragging.value ? "grabbing" : "grab"
}));
// 缩放控制
const zoom = delta => {
  const newScale = scale.value + delta;
  scale.value = Math.max(0.1, Math.min(newScale, 5)); // 限制缩放范围
};

// 滚轮缩放
const handleWheel = e => {
  e.preventDefault();
  zoom(e.deltaY > 0 ? -0.1 : 0.1);
};

// 重置
const reset = () => {
  scale.value = 1;
  flipX.value = 1;
  currentPos.value = { x: 0, y: 0 };
};

// 拖拽开始
const startDrag = e => {
  isDragging.value = true;
  startPos.value = {
    x: e.clientX - currentPos.value.x,
    y: e.clientY - currentPos.value.y
  };
  document.body.style.cursor = "grabbing"; // 改变鼠标样式
};

// 拖拽中
const handleDrag = e => {
  if (!isDragging.value) return;

  const container = imageRef.value?.$el?.parentElement;
  if (!container) return;

  const containerRect = container.getBoundingClientRect();
  const imgRect = imageRef.value?.$el.getBoundingClientRect();

  // 计算最大可移动范围
  const maxX = (imgRect.width * scale.value - containerRect.width) / 2;
  const maxY = (imgRect.height * scale.value - containerRect.height) / 2;

  let newX = e.clientX - startPos.value.x;
  let newY = e.clientY - startPos.value.y;

  // 限制边界
  newX = Math.max(-maxX, Math.min(maxX, newX));
  newY = Math.max(-maxY, Math.min(maxY, newY));

  currentPos.value = { x: newX, y: newY };
};

// 拖拽结束
const endDrag = () => {
  isDragging.value = false;
  document.body.style.cursor = ""; // 恢复鼠标样式
};

getYZlsit();
var tablelist = [];
const YZlist = JSON.parse(sessionStorage.getItem("YZlist"));
let jcbwlist = ref([]); //检查部位
let jcqklist = ref([]); //检查情况
let showzz = ref(true); //.职业类型其他有输入框
jcbwlist.value = YZlist.examination_part;
jcqklist.value = YZlist.inspect_situation;
//下拉化验项目单子,选出对用的项目
let hyxulist = e => {
  let YPlist = JSON.parse(sessionStorage.getItem("YPlist"));
  let checkdata = e.flatMap(key => YPlist[key] || []);

  let nealsit = tableData.value;

  const mapA = new Map(nealsit.map(item => [item.itemCode, item]));

  // 使用map方法遍历b，并用a中的对象替换
  let result = checkdata.map(itemB => {
    // 查找是否有匹配的itemCode
    const matchedItem = mapA.get(itemB.itemCode);
    // 如果找到匹配项，则使用a中的完整对象，否则保留原来的对象
    return matchedItem ? matchedItem : itemB;
  });
  tableData.value = result;
};
function getYZlsit() {
  seekdataApi({ dictType: "sys_laboratory_item" }).then(res => {
    hyxmlist.value = res.data.map(item => ({
      value: item.dictValue,
      label: item.dictLabel
    }));
  });
}
function xybutton() {
  fdlsit.value = [];
  if (yepage.value > 0) {
    yepage.value--;
    srcimg.value = srcList.value[yepage.value];
    fdlsit.value.push(srcimg.value);
  }
}
function sybutton() {
  //判断是否为最后一张图片
  fdlsit.value = [];
  if (yepage.value == srcList.value.length - 1) {
    return;
  } else {
    yepage.value++;
    console.log(yepage.value);
    srcimg.value = srcList.value[yepage.value];
    fdlsit.value.push(srcimg.value);
  }
}
let savebutton = () => {
  let result = hznamelist.value.find(item => item.patientId === formlist.value.patientId);
  formlist.value.patientName = result.patientName;
  formlist.value.patientId = result.patientId;
  formlist.value.reportUrl = srcimg.value;
  addjxxxApi(formlist.value).then(() => {
    ElMessage.success("新增成功");
    formlist.value = {};
  });
  getimg();
};
function addimgbutton() {}
// 修改后的上传方法
function handleFileSelect(e) {
  loading.value = true;
  const files = e.target.files;
  if (!files.length) return;

  // 创建单个 FormData 对象
  const formData = new FormData();

  // 将所有文件添加到同一个 FormData（使用相同的字段名"files"）
  for (let i = 0; i < files.length; i++) {
    formData.append("files", files[i]); // 注意：字段名必须是"files"（复数）
  }

  // 单次请求上传所有文件
  dguploadAPI(formData)
    .then(response => {
      // 处理后端返回的数据
      loading.value = false;
      ElMessage({
        message: "上传成功",
        type: "success"
      });
      getimg();
    })
    .catch(error => {
      ElMessage({
        message: "上传失败",
        type: "error"
      });
    });
}
getimg();
hzlist();
let hznamelist = ref("");

//获取图片
function getimg() {
  fdlsit.value = [];
  imageslist().then(res => {
    if (res.data?.length) {
      srcList.value = res.data.map(item =>
        item.imageUrl.startsWith("http") ? item.imageUrl : `${import.meta.env.VITE_API_BASE}${item.imageUrl}`
      );
      srcimg.value = srcList.value[0];
      fdlsit.value.push(srcimg.value);
    } else {
      srcList.value = [];
      srcimg.value = "";
      fdlsit.value.push(srcimg.value);
    }
    yepage.value = 0;
  });
}

function hzlist() {
  getMonthlyGrowth({}).then(res => {
    hznamelist.value = res.data;
  });
}
function scbutton() {
  console.log(srcimg.value);
  ElMessageBox.confirm("确定删除?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deletezpApi({
      url: srcimg.value
    }).then(res => {
      ElMessage({
        message: "删除成功",
        type: "success"
      });
      getimg();
    });
  });
}
let ybchangetwo = e => {
  if (e == "5") {
    showzz.value = false;
  } else {
    showzz.value = true;
    // form.value.examinationPart = "";
  }
};
</script>
<style scoped>
.image-viewer-container {
  position: relative;
  display: inline-block;
}

.image-container {
  height: 60vh;
  overflow: hidden; /* 改为 hidden 防止出现滚动条 */
  border: 1px solid #eee;
  position: relative;
  user-select: none; /* 防止选中图片内容 */
}

:deep(.el-image__inner) {
  width: 100%;
  height: 100%;
  object-fit: contain;
  display: block; /* 消除图片底部间隙 */
}

.controls {
  margin-top: 10px;
  display: flex;
  align-items: center;
  gap: 10px;
}

/* 强制图片填充容器 */
:deep(.el-image__inner) {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.scale-text {
  margin-left: 10px;
  font-size: 14px;
  color: #666;
}

.dzpage {
  display: flex;
  height: 100%;
}
.leftbox {
  width: 50%;
  /* background: rgb(43, 85, 223); */
}
.leftboximgbox {
  height: 60vh;
  overflow: auto;
  width: 100%;
  display: flex;
  justify-content: center;
}
.xybox {
  margin-top: 10px;
  display: flex;
  justify-content: space-around;
  align-items: center;
}
.rightbox {
  height: 80%;
  margin-left: 10px;
  flex: 1;
}
.yebox {
  margin: 0 10px;
}
.wclistbox {
  height: 50vh;
  overflow: auto;
}
.leftbg {
  display: flex;
  align-items: center;
}
.titlesbox {
  color: #909399;
  font-weight: bold;
}
.namsitens {
  color: #909399;
  font-weight: bold;
}
.bcbox {
  margin-top: 10px;
  float: right;
  /* display: flex;
  justify-content: center; */
}
.imguploadbox {
}
.imgrext {
  color: #fff;
  cursor: pointer;
  background: #009688;
  padding: 7px;
  border-radius: 5px;
  font-size: 14px;
}
</style>
<style scoped>
::v-deep(.el-image-viewer__actions) {
  top: 20%;
}
</style>
